package com.vanzo.some;

import android.content.Context;
import android.content.Intent;
import android.content.pm.*;
import android.content.pm.PackageInfo;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.util.Log;

import com.vanzo.some.appinfo.AppComparator;
import com.vanzo.some.appinfo.AppHandle;
import com.vanzo.some.appinfo.AppInfo;

import org.junit.Test;
import org.junit.runner.RunWith;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import static org.junit.Assert.*;

/**
 * Instrumentation test, which will execute on an Android device.
 *
 * @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
 */
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
    private static final String TAG = "TEST";
    private Context context;

    @Test
    public void useAppContext() throws Exception {
        // Context of the app under test.

        context = InstrumentationRegistry.getTargetContext();
        PackageManager packageManager = context.getPackageManager();
        List<android.content.pm.PackageInfo> packageInfos = packageManager.getInstalledPackages(0);

        List<AppInfo> appInfos = new ArrayList<>();
        AppInfo appInfo = null;
        for (PackageInfo packageInfo : packageInfos) {
            appInfo = new AppInfo();
            appInfo.setLabel(packageInfo.applicationInfo.loadLabel(packageManager).toString());
            appInfo.setPackageName(packageInfo.packageName);
            appInfo.setVersion(packageInfo.versionName);
            appInfo.setIcon(packageInfo.applicationInfo.loadIcon(packageManager));
            appInfo.setLauncherActivityName(getLaunchActivityName(packageManager, packageInfo.packageName));
            appInfos.add(appInfo);
        }
        Collections.sort(appInfos, new AppComparator());
        System.out.println("appInfos size = " + appInfos.size() + "");
        for (AppInfo appInfo1 : appInfos) {
            System.out.println(appInfo1.toString());
        }

    }

    private String getLaunchActivityName(PackageManager packageManager, String packageName) {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setPackage(packageName);
        List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(intent, 0);
        String mainActivityName = "";
        if (resolveInfos != null && resolveInfos.size() >= 1) {
            mainActivityName = resolveInfos.get(0).activityInfo.name;
        }
        return mainActivityName;
    }
}
